#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include "../../src/skiplist/lockfree_skiplist.h"

#define NUM_THREADS 4
#define OPS_PER_THREAD 100000
#define KEY_RANGE 10000

atomic_int ops_count = 0;

// 比较函数
int compare_ints(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

void* worker(void* arg) {
    skiplist_t* list = (skiplist_t*)arg;
    
    for (int i = 0; i < OPS_PER_THREAD; i++) {
        int op = rand() % 3;  // 0: insert, 1: find, 2: remove
        int key = rand() % KEY_RANGE;
        
        switch (op) {
            case 0: {  // insert
                int* value = malloc(sizeof(int));
                *value = key;
                if (skiplist_insert(list, key, value)) {
                    atomic_fetch_add(&ops_count, 1, memory_order_relaxed);
                } else {
                    free(value);
                }
                break;
            }
            case 1: {  // find
                if (skiplist_find(list, key)) {
                    atomic_fetch_add(&ops_count, 1, memory_order_relaxed);
                }
                break;
            }
            case 2: {  // remove
                if (skiplist_remove(list, key)) {
                    atomic_fetch_add(&ops_count, 1, memory_order_relaxed);
                }
                break;
            }
        }
    }
    return NULL;
}

int main() {
    skiplist_t list;
    pthread_t threads[NUM_THREADS];
    struct timespec start, end;
    
    if (!skiplist_init(&list, compare_ints)) {
        printf("Failed to initialize skiplist\n");
        return 1;
    }
    
    clock_gettime(CLOCK_MONOTONIC, &start);
    
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_create(&threads[i], NULL, worker, &list);
    }
    
    for (int i = 0; i < NUM_THREADS; i++) {
        pthread_join(threads[i], NULL);
    }
    
    clock_gettime(CLOCK_MONOTONIC, &end);
    
    double time_spent = (end.tv_sec - start.tv_sec) +
                       (end.tv_nsec - start.tv_nsec) / 1e9;
    
    printf("Time spent: %.2f seconds\n", time_spent);
    printf("Operations per second: %.2f\n", 
           atomic_load(&ops_count, memory_order_relaxed) / time_spent);
    printf("Final list size: %zu\n", skiplist_size(&list));
    
    skiplist_destroy(&list);
    
    return 0;
} 